package com.atguigu.kaiser;

import com.sun.org.apache.xml.internal.security.utils.Base64;

import javax.crypto.Cipher;
import java.security.*;

/**
 * @program: IDEAcode
 * @description:私钥加密私钥解密
 * @author: Mr.zjx
 * create: 2021-08-04-20-04
 **/
public class RSAdemo {
    public static void main(String[] args) throws Exception {
        String input = "张剑翔";
        //定义加密算法
        String algorithm = "RSA";
        //创建秘钥生成器对象
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        //生成秘钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        //生成公钥
        PublicKey aPublic = keyPair.getPublic();
        //生成私钥
        PrivateKey aPrivate = keyPair.getPrivate();
        //获取私钥字节数组
        byte[] privateEncoded = aPrivate.getEncoded();
        //获取公钥字节数组
        byte[] publicEncoded = aPublic.getEncoded();
        //对公钥进行base编码
        String privateKeyString = Base64.encode(privateEncoded);
        String publicKeyString = Base64.encode(publicEncoded);

        //创建加密对象
        //参数表示加密算法
        Cipher cipher = Cipher.getInstance(algorithm);
        //初始化加密
        //第一个参数：加密模式
        //第二个参数：使用时要进行加密
        cipher.init(Cipher.ENCRYPT_MODE,aPrivate);
        //私钥加密
        byte[] bytes = cipher.doFinal(input.getBytes());
        System.out.println(Base64.encode(bytes));

        //私钥解密
        cipher.init(Cipher.DECRYPT_MODE,aPublic);
        byte[] bytes1 = cipher.doFinal(bytes);
        System.out.println(new String(bytes1));
    }
}
